<?php
require "Db\DbHelper.php";
require "Tools\WebResult.php";

use Tools\WebResult;
use Db\DbHelper;

$book_id = $_REQUEST['book_id'];
$book_quantity = $_REQUEST['book_quantity'];

$logged_user = $_SESSION['user'];

// 未登录
if (empty($logged_user)) {
    WebResult::JsonFail('please_login_first！');
}

if (empty($book_id) || empty($book_quantity)) {
    WebResult::JsonEmpty();
}

// 添加当前图书到当前登录用户的购物车
$db = DBHelper::createPDO();

$stmt = $db->prepare('select * from cart where book_id =? and user_id = ?');
$stmt->bindValue(1, $book_id);
$stmt->bindValue(2, $logged_user['id']);

$stmt->execute();

$result = $stmt->fetch();

if ($result) {
    $stmt = $db->prepare('update cart set Quantity = ? where id = ?');
    $stmt->bindValue(1, $book_quantity + $result['Quantity']);
    $stmt->bindValue(2, $result['id']);

    $stmt->execute();
} else {
    $stmt = $db->prepare('insert into cart(book_id, user_id, Quantity) values(?, ?, ?)');
    $stmt->bindValue(1, $book_id);
    $stmt->bindValue(2, $logged_user['id']);
    $stmt->bindValue(3, $book_quantity);

    $stmt->execute();
}


WebResult::JsonSuccess();
